<?php

use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

include dirname(__FILE__) . DIRECTORY_SEPARATOR . "paypal" . DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR . "autoload.php";

//require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . "paypal" . DIRECTORY_SEPARATOR . "payment" . DIRECTORY_SEPARATOR . "common.php");

class paypal
{

    private $config;
    private $apiContext;

    /**
     *    支付入口
     **/

    public function config($config = null)
    {
        $this->config = $config;
        $clientId = $config['id'];
        $clientSecret = $config['key'];
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                $clientId,
                $clientSecret
            )
        );
        // TODO 正式的Time候需要关闭
        $apiContext->setConfig(
            array(
                'mode' => 'sandbox',
                'log.LogEnabled' => true,
                'log.FileName' => 'system/caches/PayPal.log',
                'log.LogLevel' => 'DEBUG',
                'cache.enabled' => true
            )
        );
        $this->apiContext = $apiContext;
    }

    public function send_pay()
    {
        $config = $this->config ;

        $payer = new \PayPal\Api\Payer();
        $payer->setPaymentMethod("paypal");

        /* 获取提交的订单号 */
        $out_trade_no = $config['code'];
        /* 获取提交的commodity名称 */
        $product_name = $config['title'];
        /* 获取提交的commodityPrice */
        $order_price = $config['money'];
        /* 获取提交的备注信息 */
        $remarkexplain = '';
        /* 支付方式 */
        $trade_mode= $config['type'];
        /* commodityPrice（包含运费），以branch为单位 *100 */
        $total_fee = $order_price;

        //设置commodity详情
        $item1 = new \PayPal\Api\Item();
        $item1->setName($product_name)
            ->setCurrency('IDR')
            ->setQuantity(1)
            ->setSku("commodity")
            ->setPrice($total_fee);
        $itemList = new \PayPal\Api\ItemList();
        $itemList->setItems(array($item1));
// 自定义用户收货地址，如果这里不定义，在支付页面能够修改，可能会误操作，与用户想等地质不一致
        $address = new \PayPal\Api\ShippingAddress();

        $address->setRecipientName("Dom")
            ->setLine1("one")
            ->setCity("USA")
            ->setState("USA")
            ->setPhone(15211111111) //收货电话
            ->setPostalCode(000000) //邮编
            ->setCountryCode('CN');

        $itemList->setShippingAddress($address);

//设置总价，运费等金额。注意：setSubtotal的金额必须与详情里计算出的总金额相等，否则会失败
//        $details = new \PayPal\Api\Details();
//        $details->setShipping(0)
//            ->setTax(0)
//            ->setSubtotal(0);
// 同上，金额要相等
        $amount = new \PayPal\Api\Amount();
        $amount->setCurrency("IDR")
            ->setTotal($total_fee);
//            ->setDetails($details);


        $transaction = new \PayPal\Api\Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription($remarkexplain)
            ->setInvoiceNumber($out_trade_no);
        /**
         * 回调
         * 当支付成功或者取消支付的Time候调用的地址
         * success=true   支付成功
         * success=false  取消支付
         */
        $redirectUrls = new \PayPal\Api\RedirectUrls();
        $redirectUrls->setReturnUrl($config['NotifyUrl'].'?success=true')//localhost/paypal/payment/exec.php?success=true
        ->setCancelUrl($config['NotifyUrl'].'?success=false');//localhost/paypal/payment/cancel.php?success=false
//        $config['ReturnUrl']
        $payment = new \PayPal\Api\Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        try {
            $payment->create($this->apiContext);
        } catch (\PayPal\Exception\PayPalConnectionException $e) {
            echo $e->getMessage();
            die();
        }

        $approvalUrl = $payment->getApprovalLink();
        header("Location: {$approvalUrl}");
        die();
    }

}

?>